<template>
  <div class="gldz-templet">
    <span class="templet-index">{{ index + 1 }}、</span>
    <el-tree
      :data="templetCheck"
      highlight-current
      default-expand-all
      :props="defaultProps"
      class="custom-tree"
    >
      <div class="custom-tree-node" :class="{'red': data.itemLevel == '2' || data.itemLevel == '3'}" slot-scope="{ node, data }">
        <span v-if="data.itemLevel==3">*</span>
        <span class="label-name">{{ node.label }}</span>
        <el-tooltip effect="dark" placement="top-start" v-if="node.level == 1">
          <div slot="content" style="max-width: 400px;line-height: 20px;">评判规则：{{ data.ruleContent }}</div>
          <i class="el-icon-question rule-content" />
        </el-tooltip>
        <div v-if="node.level == 2" class="second-width">
          <el-input
            v-if="data.isLeaf"
            :disabled="data.result === -1"
            v-model="data.score"
            placeholder="请输入得分"
            @change="inputScore(data)"
          />
          <div v-else style="color: #409EFF;">
            <el-button type="text" :disabled="data.result === -1" @click="handleNodeClick(data, node)">验收</el-button>
            <i class="el-icon-arrow-right icon-expand" />
          </div>
        </div>
        <span style="margin-left: 60px;">
          <el-tag v-if="data.result == 10 || data.result == 11" size="mini" :type="data.result == 10 ? 'success' : 'danger'">
            <span>{{ data.score }}</span>
            <!--<span>{{ data.result == 10 ? '【合格】' : '【不合格】' }}</span>-->
          </el-tag>
        </span>
        <!--甩项-->
        <span class="no-check">
          <el-checkbox v-model="data.result" :true-label="-1" :false-label="0" @change="noCheck($event, data)">甩项</el-checkbox>
        </span>
      </div>
    </el-tree>
    <el-dialog :title="templetTitle" append-to-body class="check-dialog" width="1200px" :visible.sync="showScoreDialog" :close-on-click-modal="false">
      <div class="calculate-score-wrap">
        <calculate-score v-loading="loading" :gldz-level="gldzLevel" :check-record-row="checkRecordRow" @setIsMultiAreas="setIsMultiAreas" ref="calculateScoreRef" height="75vh" @getScoreData="getScoreData" />
      </div>
      <div class="button-operate">
        <div class="level-desc">
          <div class="evaluation-level">
            <span class="evaluation-score">评价得分 :【{{ inspectionData.score }} 分】</span>
            <el-tag size="small" :type="inspectionData.result == 10 ? 'success' : 'danger'">
              <span>{{ inspectionData.result == 10 ? '【合格】' : '【不合格】' }}</span>
            </el-tag>
            <!--观感 详细得分-->
            <!--<span class="detail-score">
              <span class="score-item">户内得分：<span class="score">{{ detailScore.indoor }}</span></span>
              <span class="score-item">公区得分：<span class="score">{{ detailScore.publicArea }}</span></span>
              <span v-if="isConstruction" class="score-item">外立面得分：<span class="score">{{ detailScore.outsideWall }}</span></span>
            </span>-->
          </div>
          <div class="evaluation-desc">*注：此评价等级分数并非最终等级</div>
        </div>
        <div>
          <el-button type="primary" size="small" @click="btnSelectStandardArea" v-if="isMultiAreas">选择位置</el-button>
          <el-button type="info" size="small" @click="showScoreDialog=false">关闭</el-button>
          <el-button type="success" size="small" @click="saveTempStorage()" v-if="canSaveItems && needTemp">暂存</el-button>
          <el-button type="primary" size="small" @click="submitEvaluation()" v-if="canSaveItems">提交</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import auth from '@/plugins/auth'
import { getFileURL } from '@/api/common'
import calculateScore from './calculateScore'
import {
  cqRdcScoreItemInfo,
  saveBatchItems,
  saveTempStorage,
  getTempStorage
} from '@/api/projectInspection/courseCheck'
export default {
  /* 管理动作 样板验收 评价*/
  name: 'GldzTempletCheck',
  components: { calculateScore },
  props: {
    processType: { type: String, default: '' },
    index: {
      type: Number,
      default: 0
    },
    checkRecordRow: { // 当前 抽检过程 数据
      type: Object,
      default: () => {}
    },
    scoreType: { // 模块：防渗漏 fsl 等
      type: String,
      default: () => ''
    },
    standard: { // 当前标准
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      templetTitle: '',
      defaultProps: {
        children: 'children',
        label: 'couseName'
      },
      showScoreDialog: false,
      currentNodeData: {},
      submitParams: {
        scoreItems: [],
        taskId: '',
        score: '',
        scoreType: ''
      },
      isConstruction: true, // 土建过程 或 false 精装
      loading: false,
      inspectionData: {
        terms: [],
        score: '',
        result: 10 // 10 合格， 11 不合格
      },
      gldzLevel: '',
      isMultiAreas: false,
      checkRresult: 0, // 是否  甩项 -1
      tmpId: '',
      needTemp: true,
      parentNodeList: []
    }
  },
  computed: {
    canSaveItems() {
      // 有权保存
      const userFid = store.getters.user?.fid
      const roles = store.getters.roles || []
      const { processType, checkRecordRow } = this

      // 用户含抽检角色时，需为本项目指定的抽检人员才有权限
      if (roles.includes('GCCJRY')) return checkRecordRow.principalId === userFid

      // 不含抽检角色，有保存权限时，需为有授权的项目（项目列表即展示有授权的，这里不需判断）
      return auth.hasPermi(`cq:${processType}:saveItems`)
    },
    templetCheck() {
      // eslint-disable-next-line
      this.checkRresult = this.standard.result
      const list = [this.standard]
      return list
    }
  },
  created() { // 初始化
    const path = this.$route.path
    this.isConstruction = path.includes('ConstructionCourse')
    this.checkRresult = this.standard.result
  },
  mounted() {
    this.submitParams.taskId = this.checkRecordRow.randomId
    this.submitParams.scoreType = this.scoreType
  },
  methods: {
    saveTempStorage() {
      const params = {
        tmpId: this.tmpId,
        taskId: this.submitParams.taskId,
        parentCourseId: this.submitParams.parentCourseId,
        scoreType: this.submitParams.scoreType,
        tmpJson: JSON.stringify(this.inspectionData)
      }
      this.loading = true
      saveTempStorage(params).then(response => {
        if (response.code === 200) {
          this.msgSuccess('抽检结果暂存成功。')
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getTempStorage() {
      const params = {
        taskId: this.submitParams.taskId,
        scoreType: this.submitParams.scoreType,
        parentCourseId: this.submitParams.parentCourseId
      }
      this.loading = true
      getTempStorage(params).then(response => {
        if (response.code === 200) {
          try {
            if (response.data && response.data.length > 0) {
              this.inspectionData = JSON.parse(response.data[0].tmpJson)
              this.parentNodeList = this.inspectionData.parentNodeList
              this.tmpId = response.data[0].tmpId
              this.$nextTick(() => {
                this.$refs.calculateScoreRef.init(this.inspectionData, this.parentNodeList)
              })
            }
          } catch (e) {
            console.log(e)
          }
        }
      }).finally(() => {
        this.loading = false
      })
    },
    setIsMultiAreas(val) {
      this.isMultiAreas = val
    },
    inputScore(data) {
      if (data.score && data.score !== '0' && !Number(data.score)) {
        this.$message.error('数量请输入数字！')
        data.score = ''
        data.result = 0
      }
      if (!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(data.score)) {
        if (Number(data.score)) {
          data.score = parseFloat(parseFloat(data.score).toFixed(2))
        }
      }
      if (data.score >= 0 && data.score <= 100) {
        data.result = data.score >= 80 ? 10 : 11
        if (data.score === '') {
          data.result = 0
        }
      } else {
        this.$message.warning({ message: '分数取值范围 0 至 100。' })
        data.score = ''
        data.result = 0
      }
      if (this.templetCheck[0].children.some(item => item.result === 11)) {
        this.templetCheck[0].result = 11
        // this.templetCheck[0].score = -25
      } else {
        this.templetCheck[0].result = 10
        // this.templetCheck[0].score = 0
      }
      // 平均分
      this.templetCheck[0].score = this.getCheckAvg(this.templetCheck[0].children)
      data.originalResult = data.result
      this.$emit('getData', { score: this.templetCheck[0].score, result: this.templetCheck[0].result })
    },
    /*
    *  获取 样板验收 平均分
    * */
    getCheckAvg (children) {
      let allScore = 0
      let allItemCount = 0 // 未甩项 数量
      for (let i = 0; i < children.length; i++) {
        if (children[i].result !== -1) {
          allItemCount += 1
          if (!isNaN(parseFloat(children[i].score))) {
            allScore += parseFloat(children[i].score)
          }
        }
      }
      let avgScore = 0
      let numCeil = 0
      if (allItemCount > 0) {
        avgScore = allScore / allItemCount
        numCeil = Math.round(avgScore * 100) / 100 // 保留两位 四舍五入
      } else { // 全甩项
        numCeil = 100
      }
      return numCeil
    },
    noCheck(result, data) {
      console.log(data)
      if (data.courseCode === 'ybyspj') { // 第一级
        if (result !== -1) {
          data.children.forEach(item => {
            if (item.originalResult && item.originalResult !== -1) {
              item.result = item.originalResult
            } else {
              item.result = 0
            }
          })
          // if (data.originalResult !== -1) {
          //   data.result = data.originalResult
          // }
          this.firstLevelResult()
        } else {
          data.children.forEach(item => {
            item.result = -1
          })
        }
      } else { // 第二级
        if (result !== -1) {
          if (data.originalResult && data.originalResult !== -1) {
            data.result = data.originalResult
          } else {
            data.result = 0
          }
        }
        // 计算第一层级 结果
        this.firstLevelResult()
      }
      // if (this.templetCheck[0].result === 11) {
      //   this.templetCheck[0].score = -25
      // } else {
      //   this.templetCheck[0].score = 0
      // }
      this.templetCheck[0].score = this.getCheckAvg(this.templetCheck[0].children)
      this.$emit('getData', {score: this.templetCheck[0].score, result: this.templetCheck[0].result })
    },
    // 计算第一层级 结果
    firstLevelResult() {
      if (this.templetCheck[0].children.every(item => item.result === -1)) {
        this.templetCheck[0].originalResult = this.templetCheck[0].result
        this.templetCheck[0].result = -1
      } else {
        this.templetCheck[0].result = 10
        let result0 = true // 判断是否未填写
        for (let i = 0; i < this.templetCheck[0].children.length; i++) {
          if (this.templetCheck[0].children[i].result === 10 || this.templetCheck[0].children[i].result === 11) {
            result0 = false
          }
          if (this.templetCheck[0].children[i].result === 11) {
            this.templetCheck[0].result = 11
            break
          }
        }
        if (result0) {
          this.templetCheck[0].result = 0
        }
      }
    },
    getScoreData(inspectionData) {
      this.inspectionData = inspectionData
      this.parentNodeList = inspectionData.parentNodeList
    },
    handleNodeClick(data, node, component) {
      // console.log(data, node, component)
      this.submitParams.parentCourseId = data.courseId
      this.tmpId = ''
      if (node.isLeaf && !data.isLeaf && this.templetCheck[0].result !== -1) {
        this.templetTitle = data.couseName
        this.currentNodeData = node
        this.showScoreDialog = true
        this.getListData(data)
      }
    },
    // 甩项 重置数据
    noCheckReset(point) {
      if (point.result === -1) {
        point.badTotal = null
        point.goodTotal = null
        point.checkTotal = null
        point.deductJson = null
        point.typeJson = null
        point.isViolateStandard = false
        point.score = null
      }
    },
    // 提交数据
    submitEvaluation() {
      if (this.loading) return
      const validate = this.$refs.calculateScoreRef.validateData()
      if (validate) {
        const validateNoCheck = this.$refs.calculateScoreRef.validateNoCheck()
        if (validateNoCheck) {
          this.$message.error('子项不能全部甩项')
          return
        }
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, 10000)
        // this.showScoreDialog = false
        this.currentNodeData.data.score = this.inspectionData.score
        this.currentNodeData.data.result = this.inspectionData.result // result=11 表示不合格
        this.currentNodeData.data.originalResult = this.inspectionData.result

        // this.submitParams.score = this.inspectionData.score
        const terms = []
        terms.push(this.currentNodeData.data) // 根项
        for (let i = 0; i < this.inspectionData.terms.length; i++) {
          if (this.inspectionData.terms[i].standardList && this.inspectionData.terms[i].standardList.length > 0) {
            terms.push(...this.inspectionData.terms[i].standardList)
          }
        }
        terms.forEach(term => {
          this.noCheckReset(term)
        })
        terms.push(...this.parentNodeList)
        this.submitParams.scoreItems = terms
        this.submitParams.saveAreas = this.inspectionData.saveAreas
        this.submitParams.deleteAreas = this.inspectionData.deleteAreas
        saveBatchItems(this.submitParams).then(response => {
          if (response.code === 200) {
            this.msgSuccess('抽检结果保存成功。')

            if (this.templetCheck[0].children.some(item => item.result === 11)) {
              this.templetCheck[0].result = 11
              // this.templetCheck[0].score = -25
            } else {
              this.templetCheck[0].result = 10
              // this.templetCheck[0].score = 0
            }
            this.templetCheck[0].score = this.getCheckAvg(this.templetCheck[0].children)
            this.$emit('getData', { score: this.templetCheck[0].score, result: this.templetCheck[0].result, options: { courseId: this.submitParams.parentCourseId, scoreItemId: response.msg }})
          }
          this.inspectionData.terms = []
          this.inspectionData.score = ''
        }).finally(() => {
          this.loading = false
          this.showScoreDialog = false
        })
      }
    },
    /*
   *  初始化
   * */
    getListData(data) {
      console.log(data)
      const inspectionData = {
        terms: [],
        score: data.score,
        result: data.result
      }
      const params = {
        taskId: this.checkRecordRow.randomId,
        scoreType: this.scoreType
      }
      params.parentCourseId = data.courseId
      if (data.courseCode === 'tjlchy') {
        this.gldzLevel = '2'
      }
      if (data.courseCode === 'jzjfybys') {
        this.gldzLevel = '3'
      }
      // this.gldzLevel = params.gldzLevel
      this.loading = true
      cqRdcScoreItemInfo(params).then(
        response => {
          if (response.code === 200) {
            if (response.data.itemVOS && response.data.itemVOS.length > 0) { // 暂存判断
              if (!response.data.itemVOS[0].scoreItemId) {
                this.needTemp = true
                this.getTempStorage()
              } else {
                this.needTemp = false
              }
            }
            const itemVOS = response.data.itemVOS
            const fileItems = response.data.fileItems || []
            for (let i = 0; i < itemVOS.length; i++) {
              itemVOS[i].isViolateStandard = false
              if (!itemVOS[i].result || itemVOS[i].result === -1) {
                itemVOS[i].originalResult = 0 // 将原结果备份
              } else {
                itemVOS[i].originalResult = itemVOS[i].result
              }
              if (!itemVOS[i].itemLevel) {
                itemVOS[i].itemLevel = itemVOS[i].standardLevel
              }
              itemVOS[i].randomString = getRandomString(20)
              if (itemVOS[i].badTotal) {
                itemVOS[i].badTotal = Number(itemVOS[i].badTotal)
              }
              if (itemVOS[i].checkTotal) {
                itemVOS[i].checkTotal = Number(itemVOS[i].checkTotal)
              }
              if (itemVOS[i].goodTotal) {
                itemVOS[i].goodTotal = Number(itemVOS[i].goodTotal)
              }

              // 获取区域数据
              const standardId = itemVOS[i].standardId
              const mrqId = itemVOS[i].mrqId
              const areaList = fileItems.filter(r => r.standardId === standardId && r.mrqId === mrqId)
              areaList.map(area => {
                // checked 初始化
                area.checked = false
                area.url = getFileURL(area.fileId)
              })
              itemVOS[i].areaList = areaList
              // 备份，用于保存时，对比删除了哪些位置
              itemVOS[i].areaListBackUp = JSON.parse(JSON.stringify(areaList))

              // 违反扣分 设置 最小检测 数量
              if (itemVOS[i].ruleType === 5) {
                let ruleJson = []
                if (itemVOS[i].ruleJson) {
                  try {
                    ruleJson = JSON.parse(itemVOS[i].ruleJson)
                  } catch (e) {
                    console.log(e)
                  }
                }
                if (ruleJson.length > 0 && ruleJson[0].total) {
                  itemVOS[i].mixCheck = ruleJson[0].total
                }
              }
              if (itemVOS[i].ruleType === 9) { // 条件条款
                let conditionOptions = []
                try {
                  conditionOptions = JSON.parse(itemVOS[i].ruleJson)
                } catch (e) {
                  console.log(e)
                }
                itemVOS[i].conditionOptions = conditionOptions
                // 默认第一个条件条款
                if (!itemVOS[i].itemSel) {
                  itemVOS[i].itemSel = conditionOptions[0].name
                }
                for (let j = 0; j < conditionOptions.length; j++) {
                  if (conditionOptions[j].name === itemVOS[i].itemSel) {
                    itemVOS[i].ruleJson = conditionOptions[j].ruleJson
                    itemVOS[i].ruleType = conditionOptions[j].ruleType
                    itemVOS[i].ruleUnit = conditionOptions[j].ruleUnit
                  }
                }
              }
            }

            const formatList = this.getStandardFormat(itemVOS)
            inspectionData.terms = formatList.list
            this.parentNodeList = formatList.parentNodeList
            // inspectionData.score = response.data.score
            this.$nextTick(() => {
              this.$refs.calculateScoreRef.init(inspectionData, formatList.parentNodeList)
            })
            this.inspectionData = JSON.parse(JSON.stringify(inspectionData))
          }
        }
      ).finally(() => {
        this.loading = false
      })
      function getRandomString(len) {
        const charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789'
        const strLength = charStr.length
        let randomStr = ''
        for (let i = 0; i < len; i++) {
          const index = Math.floor(Math.random() * strLength)
          randomStr += charStr[index]
        }
        return randomStr
      }
    },
    getStandardFormat(list) {
      const inspction = {
        baseTerms: [],
        impTerms: []
      }

      // 无需区分底线与重要 条款
      // 样板验收 只展示 叶子项 标准
      const filterArr = ['tjgczldf', 'mphnjfyzyb', 'gqjfyzyb', 'wlmjfyzyb', 'tjcpssx', 'tjcnyzx', 'tjjsx', 'tjtzyzx', 'tjwzx',
        'jzgczldf', 'jzcpssx', 'jzcnyzx', 'jzjsx', 'jztzyzx', 'jzwzx'] // 非叶子项 编码
      inspction.baseTerms = list.filter((term) => !filterArr.some(item => item === term.courseCode))
      // 父节点
      const parentNodeList = list.filter((term) => filterArr.some(item => item === term.courseCode))
      console.log(parentNodeList)
      // 根据不同字段 分类
      let categoryKey = ''
      let categoryName = ''
      // if (this.scoreType === 'zl-scsl') { // 实测实量
      //   categoryKey = 'mrqId'
      //   categoryName = 'mrqName'
      // } else {
      //   categoryKey = 'tableId'
      //   categoryName = 'tableName'
      // }
      categoryKey = 'courseCode'
      categoryName = 'couseName'
      // 针对键 tableId  底线条款 进行归类的容器
      const baseContainer = { notTableId: [] }
      inspction.baseTerms.forEach(item => {
        if (item[categoryKey]) {
          baseContainer[item[categoryKey]] = baseContainer[item[categoryKey]] || []
          baseContainer[item[categoryKey]].push(item)
        } else {
          baseContainer.notTableId.push(item)
        }
      })
      const baseTerms = []
      for (const key in baseContainer) {
        if (baseContainer[key].length > 0) {
          baseTerms.push({
            // 复选框状态。空字符串-不显示，show-显示，disabled-禁用
            checkboxStatus: '',
            tableId: key,
            levelType: 'base',
            locationType: baseContainer[key][0].locationType,
            codeAncestors: baseContainer[key][0].codeAncestors,
            tableName: baseContainer[key][0][categoryName],
            standardList: baseContainer[key]
          })
        }
      }
      // console.log(baseTerms)
      // test data
      // baseTerms[0].locationType = 'hn'
      // baseTerms[0].standardList[0].locationType = 'hn'
      // baseTerms[0].standardList[1].locationType = 'wlm'
      // baseTerms[0].standardList[2].locationType = 'gq'
      // baseTerms[0].standardList[3].locationType = 'gq'
      const terms = {
        count: { base: baseTerms.length, imp: 0 },
        list: baseTerms,
        parentNodeList
      }
      return terms
    }
  }
}
</script>

<style scoped lang='scss'>
 .gldz-templet {
   font-size: 14px;
   font-weight: 700;
   padding-top: 5px;
   display: flex;
   .templet-index {
     margin-top: 5px;
   }
   .custom-tree {
     background-color: transparent;
     flex: 1;
     min-width: auto !important;
     /deep/.el-tree-node__content{
       height: auto;
     }
     .el-tree-node {
       white-space: normal;
     }
     .custom-tree-node {
       display: flex;
       line-height: 36px;
       align-items: center;
       width: 100%;
       font-size: 14px;
       .label-name {
         display: inline-block;
         min-width: 140px;
       }
       .rule-content {
         cursor: pointer;
         font-size: 16px;
         color: #333333;
         margin-left: 20px;
         &:hover {
           color: #409EFF;
         }
       }
       .second-width {
         display: inline-block;
         width: 200px;
       }
       .check-btn {
         font-size: 14px;
         font-weight: normal;
       }
       .icon-expand {
         font-size: 16px;
       }
     }
   }
   .no-check {
     flex: 1;
     text-align: right;
     margin:5px 20px 0 10px;
   }
 }
 .check-dialog {
   /deep/.el-dialog__body {
     padding-top: 0;
   }
 }
  .calculate-score-wrap {

  }
 .evaluation-level {
   color: #333;
   font-size: 18px;
   box-sizing: border-box;
   font-weight: 700;
   display: flex;
   align-content: center;
   .detail-score {
     font-size: 14px;
     font-weight: normal;
     .score-item {
       margin-left: 30px;
       .score {
         font-weight: 700;
         font-size: 16px;
       }
     }
   }
 }
 .evaluation-desc {
   font-size: 12px;
   color: #909399;
   margin-top: 6px;
 }
 .button-operate {
   border-top: 1px #DCDFE6 solid;
   padding: 10px 30px 0;
   display: flex;
   justify-content: space-between;
   margin: 10px 10px -20px 10px;
   align-items: center;
   .level-desc {
     display: flex;
     flex-direction: column;
   }
 }
  .red {
    color: #f56c6c;
  }
</style>
